package cn.edu.gdut.deepcode.service.impl;

import cn.edu.gdut.deepcode.annotation.CanvasIdCheckPoint;
import cn.edu.gdut.deepcode.component.SimpleGlobalLock;
import cn.edu.gdut.deepcode.domain.po.CanvasSnapshot;
import cn.edu.gdut.deepcode.domain.po.Result;
import cn.edu.gdut.deepcode.mapper.CanvasSnapshotMapper;
import cn.edu.gdut.deepcode.service.ICanvasSnapshotService;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collections;
import java.util.List;

import static cn.edu.gdut.deepcode.constant.CacheConstant.CANVAS_SNAPSHOT_CACHE_KEY_PREFIX;
import static cn.edu.gdut.deepcode.constant.ReqRespConstant.COMMON_SUCCESSFUL_MSG;

/**
 * <p>
 * 画布快照表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-11
 */
@Slf4j
@RequiredArgsConstructor
//@Service
public class CanvasSnapshotNoCacheServiceImpl extends ServiceImpl<CanvasSnapshotMapper, CanvasSnapshot> implements ICanvasSnapshotService {

    private final StringRedisTemplate redisTemplate;
    private final SimpleGlobalLock globalLock;

    @Override
    @CanvasIdCheckPoint
    public Result<?> directSaveSnapshot(Long canvasId, String canvasData) {
        // 创建快照对象
        CanvasSnapshot canvasSnapshot = new CanvasSnapshot();
        // 设置其他数据
        canvasSnapshot
                .setCanvasId(canvasId)
                .setCanvasData(canvasData)
                .setOffset(-1L);// 直接存储时偏移量为-1
        save(canvasSnapshot);
        clearCache(canvasId);
        return Result.success();
    }



    @Override
    @CanvasIdCheckPoint
    public Result<String> getSnapshotById(Long canvasId) {
        // 查数据库
        Page<CanvasSnapshot> page = new Page<>(1, 1);
        page.addOrder(OrderItem.desc("id"));
        lambdaQuery()
                .select(CanvasSnapshot::getCanvasData)
                .eq(CanvasSnapshot::getCanvasId, canvasId)
                .page(page);
        List<CanvasSnapshot> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            records = Collections.emptyList();
        }

        String canvasData = records.size() > 0 ?
                records.get(0).getCanvasData() : "";
        // 返回数据
        return Result.success(COMMON_SUCCESSFUL_MSG, canvasData);
    }

    @Override
    public void deleteSnapshotById(Long canvasId) {
        lambdaUpdate()
                .eq(CanvasSnapshot::getCanvasId,canvasId)
                .remove();
        clearCache(canvasId);
    }


    public void clearCache(Long canvasId) {
        // 清空缓存
        redisTemplate.delete(CANVAS_SNAPSHOT_CACHE_KEY_PREFIX+ canvasId);
    }

    public void genSnapshot(Long canvasId) {

    }
}
